/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.web.service.support.storage.mgt;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vacoor.nothing.common.util.IOUtils;

import java.io.*;

/**
 * 本地存储实现
 *
 * @author vacoor
 */
public class LocalStorageManagerImpl extends GeneralStorageManager {
    private static final Logger LOG = LoggerFactory.getLogger(LocalStorageManagerImpl.class);

    @Override
    public boolean exists(String path) {
        return new File(path).exists();
    }

    @Override
    public boolean readTo(String path, OutputStream out, boolean closeOut) {
        InputStream is = readAsStream(path);
        if (null == is) {
            return false;
        }
        try {
            IOUtils.flow(is, out, true, closeOut);
        } catch (IOException ioe) {
            LOG.warn("read {} failure: {}", path, ioe);
            return false;
        }
        return true;
    }

//    @Override
    public InputStream readAsStream(String path) {
        File file = readAsFile(path);
        try {
            return null == file ? null : new FileInputStream(file);
        } catch (FileNotFoundException fnfe) {
            throw new RuntimeException("不应该出现的异常");
        }
    }

//    @Override
    public File readAsFile(String path) {
        File file = new File(path);
        return file.exists() ? file : null;
    }

    @Override
    public void store(InputStream is, String path) throws IOException {
        File file = new File(path);
        File dir = file.getParentFile();

        if (!dir.exists()) {
            dir.mkdirs();
        }

        try {
            IOUtils.flow(is, new FileOutputStream(file), true, true);
        } catch (IOException ioe) {
            file.delete();
            throw ioe;
        }
    }

    @Override
    public void mkdirs(String path) {

    }

    @Override
    public void close() {}
}
